package com.gitee.smalllog.logback.appender;

import ch.qos.logback.classic.spi.ILoggingEvent;
import com.alibaba.fastjson.JSON;
import com.gitee.smalllog.core.MessageAppenderFactory;
import com.gitee.smalllog.core.client.RedisClient;
import com.gitee.smalllog.core.constant.LogMessageConstant;
import com.gitee.smalllog.core.model.BaseLogMessage;
import com.gitee.smalllog.core.model.RunLogMessage;
import com.gitee.smalllog.core.model.Settings;
import com.gitee.smalllog.core.utils.*;
import com.gitee.smalllog.logback.appender.pub.ClassicSmallLogPublisher;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicBoolean;

@Data
public class RedisAppender extends AbstractLogAppender<ILoggingEvent> {

    private RedisClient redisClient;

    private static final ThreadPoolExecutor threadPoolExecutor
            = ThreadPoolUtil.getPool();

    private static final AtomicBoolean INIT = new AtomicBoolean();

    public RedisAppender() {
    }

    public RedisAppender(Settings settings) {
        super(settings);
    }

    @Override
    protected void appendInternal(ILoggingEvent loggingEvent) {
        //获取原来logback的 loggername
        String targetLogger = loggingEvent.getLoggerName();
        //配置文件的loggerName
        String loggerName = settings.getLoggerName();
        if (loggerName != null && loggerName.equals(targetLogger)) {
            return;
        }

        //只针对开发自己定义的日志收集
        if(TraceId.logTraceID.get().isEmpty()){
            return;
        }

        if (this.redisClient == null) {
            MessageAppenderFactory.initQueue(settings.getMaxQueueSize());
            this.redisClient = RedisClient
                    .getInstance(settings.getRedisHost(), settings.getRedisPort(), settings.getRedisAuth(), 0);

            // 当多并发情况下若redisClient为空时会多次执行以下代码，因此增加是否已初始化的判断
            if (INIT.compareAndSet(false, true)) {
                for (int a = 0; a < settings.getThreadPoolSize(); a++) {
                    threadPoolExecutor.execute(() -> {
                        MessageAppenderFactory.startRunLog(this.redisClient, settings.getMaxQueueSize(),
                                settings.isCompressor() ? LogMessageConstant.LOG_KEY_COMPRESS : LogMessageConstant.LOG_KEY,
                                settings.isCompressor());
                    });
//					threadPoolExecutor.execute(() -> {
//						MessageAppenderFactory.startTraceLog(this.redisClient, settings.getMaxQueueSize(),
//								settings.isCompressor()  ? LogMessageConstant.LOG_KEY_TRACE_COMPRESS : LogMessageConstant.LOG_KEY_TRACE, settings.isCompressor());
//					});
                }
            }
        }

        final BaseLogMessage logMessage = LogMessageUtil.getLogMessage(settings.getAppName() , settings.getEvn(), loggingEvent);
        RunLogMessage runLogMessage = (RunLogMessage)logMessage;
        runLogMessage.setLogTitle(loggingEvent.getMarker().getName());
        final String message = LogMessageUtil.getLogMessage(runLogMessage);
        System.out.println("数据发送成功：" + message);
        MessageAppenderFactory.pushRundataQueue(message);
    }

    protected ClassicSmallLogPublisher buildElasticsearchPublisher() throws IOException {
        return new ClassicSmallLogPublisher(getContext(), errorReporter, settings, properties);
    }

}
